﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Vit.Common
{
    public class CachableQuery<T> : Vit.Common.ICachable
    {
        private Func<IQueryable<T>, object[], string> cacheKeyBuilder;

        public CachableQuery(IQueryable<T> query)
            : this(query, null)
        {
        }

        public CachableQuery(IQueryable<T> query, Func<IQueryable<T>, object[], string> keyBuilder = null)
        {
            Query = query;
            this.cacheKeyBuilder = keyBuilder;
        }

        #region ICachable Members

        public string BuildCacheKey(object[] paras)
        {
            if (cacheKeyBuilder != null)
                return cacheKeyBuilder(Query, paras);
            Type type = typeof(T);
            string keySuffix = string.Empty;
            if (paras != null)
            {
                foreach (var p in paras)
                    keySuffix += string.Concat("[", p == null ? "NULL" : p.ToString(), "]");
            }
            return string.Format("{0}:Query:{1}", type.FullName, Query, keySuffix);
        }

        public IEnumerable<string> DependencySet { get; set; }

        #endregion

        public IQueryable<T> Query { get; set; }
    }
}
